<?php
namespace Admin\Controller;

class CategoryController extends PublicController
{
    //分类显示
    public function index()
    {
        $pid = empty($_GET['pid'])?'0':$_GET['pid'];
        $list = D('Category')->where('pid='.$pid)->select();
        // v($list);exit;
        if ($pid != '0') {
            $pname = D('Category')->where('id='.$pid)->getField('cname');
            $this->assign('pname', $pname);
        }
        $this->assign('list', $list);
        $this->display('Category/index');
    }

    //添加分类
    public function add()
    {
        // v($_POST);exit;
        $cate = D('Category');
        if (IS_POST) {
            //过滤数据
            if (!D('Category')->create()) {
                $this->error(D('Category')->getError());
            } else {
                if (D('Category')->add() > 0) {
                    $this->success('添加成功',U('Category/index'));
                } else {
                    $this->error('添加失败');
                }
            }
        }else{
            $this->error('禁止非法添加');
        }
    }

    //编辑子类
    public function edit()
    {
        // v($_POST);exit;
        $cate = D('Category');
        if (IS_POST) {
            //过滤数据
            if (!D('Category')->create()) {
                $this->error(D('Category')->getError());
            } else {
                if (D('Category')->save() > 0) {
                    $this->success('编辑成功',U('Category/index'));
                } else {
                    $this->error('编辑失败');
                }
            }
        }else{
            $this->error('禁止非法编辑');
        }
    }

    //删除子类
    public function del()
    {
        // v($_GET);exit;
        if ($_GET['pid'] == '0') {
            $this->error('顶级分类不能被删除');
        }
        $_GET['id'] = I('get.id/d');
        $cate = D('Category');
        if (IS_GET) {
            //过滤数据
            if ($_GET['pid'] == '0') {
                $this->error('不能传非法数据');
            } else {
                if (D('Category')->delete($_GET['id']) > 0) {
                    $this->success('删除成功',U('Category/index'));
                } else {
                    $this->error('删除失败');
                }
            }
        }else{
            $this->error('禁止非法删除');
        }
    }

    //分类显示
    public function status()
    {
        if ($_GET['display'] != 1 && $_GET['display'] != 0) {
            $this->redirect('Category/index');
        }

        $display = ($_GET['display'] == '1')?'0':'1';
        M('Category')->where(array('id'=>$_GET['id']))->save(array('display'=>$display));
        $this->redirect('Category/index');
    }
}
